package com.lagou.sqlSession;

import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;

import java.lang.reflect.*;
import java.util.List;

/**
 * @Title: IPersistence
 * @Description:
 * @Author: Wenfeng Cheng
 * @Date: 2020-11-28 10:35
 * @Version: 1.0.0
 */
public class DefaultSqlSession implements SqlSession {

    private Configuration configuration;

    private SimpleExecutor simpleExecutor = new SimpleExecutor();

    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public <E> List<E> selectList(String statementId, Object... params) throws Exception {
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
        List<E> query = simpleExecutor.query(configuration, mappedStatement, params);
        return query;
    }

    @Override
    public <T> T selectOne(String statementId, Object... params) throws Exception {
        List<Object> objects = selectList(statementId, params);
        if(objects.size() == 1){
            return (T) objects.get(0);
        }else{
            throw new RuntimeException("查询结果为空或查询结果有多个");
        }
    }

    @Override
    public int insert(String statementId, Object... params) throws Exception {
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
        int count = simpleExecutor.update(configuration, mappedStatement, params);
        return count;
    }

    @Override
    public int updateById(String statementId, Object... params) throws Exception {
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
        int count = simpleExecutor.update(configuration, mappedStatement, params);
        return count;
    }

    @Override
    public int deleteById(String statementId, Object... params) throws Exception {
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
        int count = simpleExecutor.update(configuration, mappedStatement, params);
        return count;
    }

    @Override
    public <T> T getMapper(Class<?> mapperClass) {
        //使用JDK动态代理为Dao接口生成代理对象，并返回
        Object proxyInstance = Proxy.newProxyInstance(DefaultSqlSession.class.getClassLoader(), new Class<?>[]{mapperClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //底层都是执行JDBC代码，根据不同情况来调用selectList和selectOne
                //准备参数1 ：statementId sql的唯一标识：namespace.id = 接口的全限定名.方法名
                //方法名
                String methodName = method.getName();
                String className = method.getDeclaringClass().getName();
                String statementId = className + "." + methodName;
                //准备参数2 params:args
                if(methodName.contains("select") || methodName.contains("find")){
                    //获取被调用方法的返回值类型
                    Type genericReturnType = method.getGenericReturnType();
                    //判断是否进行了 泛型类型参数化
                    if(genericReturnType instanceof ParameterizedType){
                        List<Object> objects = selectList(statementId, args);
                        return objects;
                    }else{
                        return selectOne(statementId,args);
                    }
                }else if(methodName.contains("insert")){
                    return insert(statementId,args);
                }else if(methodName.contains("update")){
                    return updateById(statementId,args);
                }else if(methodName.contains("delete")){
                    return deleteById(statementId,args);
                }else{
                    throw  new RuntimeException("未找到对应的方法名");
                }
            }
        });
        return (T) proxyInstance;
    }
}
